import psutil

pids = psutil.pids()
connect = psutil.net_connections()
ports = []
jsq = 0


for conn in connect:
    # 跳过ipv6
    if hasattr(conn.laddr, 'ip') and ':' in conn.laddr.ip:
        continue
    laddr_ip = conn.laddr.ip if hasattr(conn.laddr, 'ip') else "None"
    laddr_port = conn.laddr.port if hasattr(conn.laddr, 'port') else "None"
    raddr_port = conn.raddr.port if hasattr(conn.raddr,'port') else "None"
    pid = conn.pid if conn.pid else 0
    try:
        P_name = psutil.Process(pid).name() if pid else "None"
    except psutil.NoSuchProcess:
        P_name = "Unknown"
    ports.append({
        'ip': laddr_ip,
        'Lport': laddr_port,
        'Rport': raddr_port,
        'pid': pid,
        'P_name': P_name
    })




def get_pid_port(pid):
    res = list(filter(lambda item:item.get("pid") == pid, ports))
    return res

def get_pname_port(P_name):
    res = list(filter(lambda item:item.get("P_name") == P_name, ports))
    return res
print (ports)
# print("##########################")

#pid查询
# print(get_pid_port(int(input())))

# #P_name查询
# print(get_pname_port(input()))